package zpx.dao;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate4.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;

import zpx.idao.IMenuDao;
import zpx.model.Material;
import zpx.model.Menu;
import zpx.model.Pager;
import zpx.model.SystemContext;


@Repository("menuDao")
public class MenuDao extends HibernateDaoSupport implements IMenuDao{
	
	@Resource
	public void setSuperSessionFactory(SessionFactory sessionFactory) {
		this.setSessionFactory(sessionFactory);
	}
	
	@Override
	public void add(Menu menu) {
		this.getSessionFactory().getCurrentSession().save(menu);
		
	}

	@Override
	public void update(Menu menu) {
		this.getSessionFactory().getCurrentSession().update(menu);
		
	}

	@Override
	public void delete(String id) {
		Menu menu = this.load(id);
		this.getHibernateTemplate().delete(menu);
	}

	@Override
	public Menu load(String id) {
		if(id==null ||"".equals(id)){
            return null;
        }
        StringBuffer sql = new StringBuffer();
        sql.append("from Menu as m where m.id= :id ");
        Query query = this.getSessionFactory().getCurrentSession().createQuery(sql.toString());
        query.setParameter("id", id); 
        return (Menu) query.uniqueResult();
		//return this.getHibernateTemplate().load(Menu.class, id);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Menu> list() {
		return this.getSessionFactory().getCurrentSession().createQuery("from Menu").list();
	}

	@SuppressWarnings("unchecked")
	@Override
	public Pager<Menu> find() {
		int size = SystemContext.getSize();
		int offset = SystemContext.getOffset();
		Query query = this.getSessionFactory().getCurrentSession().createQuery("from Menu");
		query.setFirstResult(offset).setMaxResults(size);		
		List<Menu> datas = query.list();
		Pager<Menu> us = new Pager<Menu>();
		us.setDatas(datas);
		us.setOffset(offset);
		us.setSize(size);
		long total = (Long)this.getSessionFactory().getCurrentSession()
					.createQuery("select count(*) from Menu")
					.uniqueResult();
		us.setTotal(total);
		return us;
	}

	@Override
	public Menu loadByMenuname(String name) {
		return (Menu)this.getSessionFactory().getCurrentSession().createQuery("from Menu where name=?")
				.setParameter(0, name).uniqueResult();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Menu> pMenulist() {
		return this.getSessionFactory().getCurrentSession().createQuery("from Menu where pid=0").list();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Menu> cMenulist(String id) {
		return (List<Menu>)this.getSessionFactory().getCurrentSession().createQuery("from Menu where pid=? order by orderid")
				.setParameter(0, id).list();
	}

}
